<?php
/**
 * Created by PhpStorm.
 * User: varcher
 * Date: 2017/11/7
 * Time: 下午11:19
 */

require_once "BifrostWeOA.php";

abstract class Bifrost
{
    private $username               =   "";
    private $password               =   "";
    protected $zabbixUrl            =   "";
//    protected $zabbixAPI            =   "";
    protected $zabbixAccessToken    =   null;
    protected $zabbixAccessId       =   1;
//    protected

    public function zabbixStart(string $zabbixUsername, string $zabbixPassword, string $zabbixUrl):bool
    {
        $this->username = $zabbixUsername;
        $this->password = $zabbixPassword;
        $this->zabbixUrl = $zabbixUrl;

        return $this->zabbixLogin();
    }

    public function zabbixLogin():bool
    {
        $zabbixMethod             =   "user.login";
        $zabbixParams['user']     =   $this->username;
        $zabbixParams['password'] =   $this->password;
        $result = $this->zabbixRequest($zabbixMethod, $zabbixParams);
        if (isset($result['result'])) {
            $this->zabbixAccessToken = $result['result'];
            return true;
        } else {
            var_dump($result);  //todo:handle all failure of zabbix_api call
            return false;
        }
    }

    protected function zabbixRequest(string $zabbixMethod, array $zabbixParams):array
    {
        $sendInfo['jsonrpc']    =   "2.0";
        $sendInfo['method']     =   $zabbixMethod;
        $sendInfo['params']     =   $zabbixParams;
        $sendInfo['id']         =   $this->zabbixAccessId ++;
        $sendInfo['auth']       =   $this->zabbixAccessToken;

        return $this->zabbixSend($sendInfo, "POST", true);

    }

    protected function zabbixSend($sendInfo, string $method = "POST", bool $jsonEncodeNeeded = false):array
    {
        $requireURL	    =	"http://{$this->zabbixUrl}/api_jsonrpc.php";

        $curlHandler = curl_init();
        curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curlHandler, CURLOPT_HEADER,         false);
        curl_setopt($curlHandler, CURLOPT_TIMEOUT, 	       10);
        curl_setopt($curlHandler,CURLOPT_SSL_VERIFYPEER,false); ;
        curl_setopt($curlHandler, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curlHandler, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        if ($jsonEncodeNeeded)
        {
            $sendingMessage = json_encode($sendInfo, JSON_PRETTY_PRINT);
        }
        else
        {
            $sendingMessage = $sendInfo;
        }

        if("POST" == $method)
        {
//            var_dump($sendingMessage);
            curl_setopt($curlHandler, CURLOPT_POST, true);
            curl_setopt($curlHandler, CURLOPT_POSTFIELDS, $sendingMessage);
            curl_setopt($curlHandler, CURLOPT_URL,  $requireURL);
        }
        else
        {
            curl_setopt($curlHandler, CURLOPT_URL,  $requireURL."?".$sendingMessage);
        }

        $output = curl_exec($curlHandler);

        if($output === FALSE ){
            throw new Exception("CURL call failed, reason = ".curl_error($curlHandler));
        }

        curl_close($curlHandler);
        $result =  json_decode($output, true);

        if (isset($result['error'])) {
            throw new Exception("Zabbix Call Error:{$result['error']['message']} / {$result['error']['data']}", $result['error']['code']);
        }

        if (!isset($result['jsonrpc']) || $result['jsonrpc'] != '2.0' || !isset($result['result'])){
            throw new Exception("Zabbix Call Error: Return String cannot be resoved. {$result}");
        }
        else {
            return $result;
        }
    }

    protected function secsToStr(int $secs, string $minScale="MIN"):string
    {
        $r = '';
        $minScaleValue = 3;
        switch ($minScale) {
            case "DAY":
                if ($secs < 86400) {
                    return "少于1天";
                }
                $minScaleValue = 0;
                break;
            case "HOUR":
                if ($secs < 3600) {
                    return "少于1小时";
                }
                $minScaleValue = 1;
                break;
            case "MIN":
                if ($secs < 60) {
                    return "少于1分钟";
                }
                $minScaleValue = 2;
                break;
            default:break;
        }
        if($secs>=86400) {
            $days = floor($secs / 86400);
            $secs = $secs % 86400;
            $r = $days . '天';
        }
        if($secs>=3600 && $minScaleValue > 0) {
            $hours = floor($secs / 3600);
            $secs = $secs % 3600;
            $r .= $hours . '小时';
        }
        if($secs>=60 && $minScaleValue > 1) {
            $minutes = floor($secs / 60);
            $secs = $secs % 60;
            $r .= $minutes . '分';
        }
        if ($minScaleValue > 2) {
            $r.=$secs.'秒';
        }
        return $r;
    }

    protected function severityToStr(string $severityIn, bool $switchEmoji = false): string
    {
        $severityCHN = array("未定义", "通知", "警告", "问题", "严重", "灾难");
        $severityEMJ = array();
        $severity = (int)$severityIn;

        if ($severity < 0 || $severity > 5) {
            throw new Exception("Trigger Severity {$severity} invalid.");
        }

        $severityStr = $severityCHN[$severity];

        return $severityStr;
    }
}
